//
// Created by wlly-lzh on 24-5-24.
//

#include <stdlib.h>
#include "file.h"

int compare_head(const void *A,const void * B){ //降序
	return ((head *)B)->count - ((head  *)A)->count;
}

int head_of_file(FILE * file,head * H,int *length){
	unsigned char ch;
	int l=0;
	int num=0; // 统计出现的字符种数
	while (fread(&ch,sizeof(char),1,file)==1){
		(*(H+ch)).count++;
		l++;
	}
	*length=l;
	// 初始化
	for(int i=0; i<SIZE_HEAD; ++i){
		if((*(H+i)).count != 0){
			(*(H+i)).ch=(unsigned char)i;
			num++;
		}else{
			(*(H+i)).ch=(unsigned char)0; //正常情况下 文本文件中没有'\0'
		}
		(*(H+i)).Parent=-1; // 此时不存在父结点
		(*(H+i)).Right=-1;  // 也不存在子结点
		(*(H+i)).Left=-1;
	}
	// 排序(降序)
	qsort(H,SIZE_HEAD,sizeof(head),compare_head);
	return num;
}

unsigned char StrtoBin(char * ch){
	unsigned char bin=0;
	unsigned char tmp;
	for(int i=0; i<8; ++i){
		tmp = 0;
		tmp = (tmp | (ch[i] - '0')) << (7 - i);
		bin = bin | tmp;
	}
	return bin;
}
void BintoStr(char bin,char * ch){
	for(int i=7; i>=0; --i){
		if(bin & 1){
			ch[i]='1';
		}else{
			ch[i]='0';
		}
		bin = bin >> 1;
	}
	ch[8]='\0';
}
void init_storage_tree(head * H,storage_tree * T){
	for(int i=0; i<SIZE_HEAD; ++i){
		T[i].ch=H[i].ch;
		T[i].Parent=H[i].Parent;
		T[i].Left=H[i].Left;
		T[i].Right=H[i].Right;
	}
}
